% Matlab Code for replication of "Optimal Debt Maturity and Firm Investment"
% by J. Jungherr and I. Schott, September 2020
% Compute model moments

% Auxiliary variables
Y       = PARMS.Z'.*(cap_pol.^PARMS.PSI.*lab_pol.^(1-PARMS.PSI)).^PARMS.ZETA;
ISS     = PARMS.ETA*(std_pol).^2;
DC      = PARMS.XI*ktilde_pol; % default costs
I       = PARMS.DELTA * cap_pol;
C       = (Y(:) - PARMS.F - ISS(:)  - DC(:) - I(:))'*probst;
L_d     = lab_pol(:)'*probst; 
Mstar   = ( PARMS.W / ( (C^PARMS.RHO) * (L_d^PARMS.THETA) ) )^(1/(PARMS.THETA+PARMS.RHO));
% Labor supply 
L_s     = (PARMS.W * ( (Mstar*C)^(-PARMS.RHO)) )^(1/PARMS.THETA);
% Aggregate capital
K_d_star= cap_pol(:)'*probst*Mstar;
% GDP
Y_star  = (Y(:) - PARMS.F - ISS(:)  - DC(:) )'*probst*Mstar;
% Aggregate consumption from resource constraint 
C_res   = Y_star - PARMS.DELTA*K_d_star;

 
% Average leverage
moment.meanlev      = lev_pol(:)'*probst / sum(probst); 
% Average default rate
moment.defrate      = def_pol(:)'*probst / sum(probst); 
% Average short-term credit spread
stspr               = ((1+PARMS.C)./ps_pol(:)).^4 -  (1 + PARMS.R)^4;
moment.meanspread   = stspr'*probst / sum(probst);
% Value of entry
moment.valentry     = value_pol(1);
% Mass of firms
moment.mass         = sum(probst)*Mstar;
% Average capital
moment.AvgK         = cap_pol(:)'*probst/sum(probst);
% Aggregate capital
moment.AggK         = cap_pol(:)'*probst*Mstar;
% GDP
moment.GDP          = Y_star;
% Consumption
moment.Cons         = C_res;
    